'use strict';

/**
 * JWT认证中间件
 * @param options
 */
module.exports = options => {
  return async function authMiddleware(ctx, next) {
    try {
      // 从请求头中获取token
      const token = ctx.request.header.authorization;
      if (!token) {
        ctx.status = 405;
        ctx.body = { code: 405, message: '未提供token', data: null };
        return;
      }

      // 验证token
      const decoded = ctx.app.jwt.verify(token.replace('Bearer ', ''), ctx.app.config.jwt.secret);
      ctx.state.user = decoded;
      await next();
    } catch (error) {
      if (error.name === 'TokenExpiredError') {
        ctx.status = 405;
        ctx.body = { code: 405, message: 'token已过期', data: null };
        return;
      } else if (error.name === 'JsonWebTokenError') {
        ctx.status = 405;
        ctx.body = { code: 405, message: '无效的token', data: null };
        return;
      } else if (error.status === 405) {
        // 如果错误已经是405，则直接返回
        ctx.status = 405;
        ctx.body = { code: 405, message: error.message, data: null };
        return;
      }
      // 对于其他错误，让错误处理中间件处理
      throw error;

    }
  };
};
